package com.cisco.nm.pf.dbservice.resources;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import com.cisco.nm.pf.dbservice.dbutil.DatabaseUtil;
import com.cisco.nm.pf.dbservice.resultbuilder.DBResultBuilder;
import com.sun.jersey.api.view.Viewable;

@Path("/dbaccess")
public final class DBAccessResource {
	
	@POST
	@Produces("text/html")
	public Response getData(@FormParam("txtLogin") String login,
							@FormParam("txtpasswd") String password,
							@FormParam("txtServiceId") String sid,
							@FormParam("txtQuery") String query){
		
		Map<String,String> userInfoMap = new HashMap<String,String>();
		userInfoMap.put("username",login);
		userInfoMap.put("password",password);
		userInfoMap.put("sid",sid);
		userInfoMap.put("query", query);
		System.out.println("inside get data " + userInfoMap);
		
		JSONObject jsonObj = new JSONObject();
		DatabaseUtil resultBuilder = DBResultBuilder.getDBUtil();
		JSONObject json = resultBuilder.executeQuery(userInfoMap, query);
		JSONArray array = null;
		try {
			jsonObj.put("header", json.getJSONArray("HEADER"));
			array = json.getJSONArray("HEADER");
			System.out.println(jsonObj.length());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
		URI reDirectURI = null;		
		try {
			reDirectURI = new URI("../dbaccessresult.jsp");
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//		return Response.temporaryRedirect(reDirectURI).entity(userInfoMap.toString()).type(MediaType.TEXT_HTML_TYPE).build();
		
		return Response.ok(new Viewable("/dbaccessresult.jsp",array)).type(MediaType.TEXT_HTML_TYPE).build();
		
	}
	
	private JSONArray getSimpleArray(){
		ArrayList<String> list = new ArrayList<String>();
		list.add("a");
		list.add("b");
		list.add("c");
		list.add("d");
		JSONArray array = new JSONArray(list);
		return array;
	}
}
